package com.qf.config;

import com.qf.security.QfAuthenticationEntryPoint;
import com.qf.security.QfBasicAuthenticationFilter;
import com.qf.security.QfLogoutHandler;
import com.qf.security.QfUsernamePasswordAuthenticationFilter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.data.redis.RedisProperties;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.core.RedisOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;

@Configuration
@ConditionalOnClass(RedisOperations.class)
@EnableConfigurationProperties(RedisProperties.class)
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    @Autowired
    RedisTemplate redisTemplate;

    @Autowired
    UserDetailsService userDetailsService; //查询数据库中的用户/权限/在redis中存储权限信息

    @Autowired
    PasswordEncoder passwordEncoder;
    @Bean
    public BCryptPasswordEncoder bCryptPasswordEncoder(){
        return new BCryptPasswordEncoder();
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.cors();

        http.exceptionHandling()
                .authenticationEntryPoint(new QfAuthenticationEntryPoint())
                .and()
                .csrf()
                .disable()

                .authorizeRequests()
                .antMatchers("/user/login","/**").permitAll() //放开的请求
                .anyRequest()
                .authenticated()

                //注销
                .and()
                .logout()
                .logoutUrl("/logout") //注销的接口
                .addLogoutHandler(new QfLogoutHandler(redisTemplate))
                .and()


                //认证
                .addFilter(new QfUsernamePasswordAuthenticationFilter(this.authenticationManager(),redisTemplate))
                //权限: 从配置类中获得认证管理器传给用于处理权限的类
                .addFilter(new QfBasicAuthenticationFilter(this.authenticationManager(),redisTemplate))

                //开启basic认证
                .httpBasic();
    }

}
